<template>
	<view class="workorder">
		<SearchBar @search="towOrderSearch" />
		<view class="ag-spacer20"></view>
		<Tabs @tabChange="onTabChange" :tabs="tabs" />
		<block v-for="(listItem, index) in workOrderList" :key="index">
			<WoItem v-for="(orderitem, oindex) in listItem" :key="orderitem.WoId" :typealias="firstChar(orderitem.WoType)"
			 :workorder="orderitem" :showBtnObject="displayBtn(orderitem)" @onOpenMap="openAddressMap" @onReservationClick="onReservationClick"
			 :workOrderState="workOrderState" @onAcceptorderClick="onAcceptorderClick" @onVisitClick="onVisitClick"
			 @completeWOrder="onCompleteWOrder" @valuateClick="onvaluateClick" @reCompleteWOrder="onReCompleteWOrder" />
		</block>
		<tui-scroll-top :scrollTop="scrollTop" :top="1000"></tui-scroll-top>
		<ReservationPoPup ref="reservationPoPup" :orderDetailData="orderDetailData" @onSubmitReservation="onSubmitReservation" />
		<VisitPoPup ref="visitPoPup" :orderDetailData="orderDetailData" :orderVisitData="VisitData" @onVisit="onSubmitVisit"
		 @changeMilestone="onChangeMilestone" @changeStreet="onChangeStreet" />
		<appraisePopup :qrval="qrAppraise" ref="appraisePopup" />
	</view>
</template>
<script>
	import ReservationPoPup from '../../components/ReservationPoPup'
	import VisitPoPup from '../../components/VisitPoPup';
	import SearchBar from '../../components/SearchBar';
	import WoItem from '../../components/WoItem';
	import Tabs from '../../components/Tabs';
	import Utils from '../../common/utils';
	import workorderbehavior from './workorderbehavior';
	import permissionCommon from "@/common/permissionCommon"
	import AGInput from '../../components/AGInput';
	import appraisePopup from '@/components/AppraisePopup';
	import constant from "@/common/constant";
	import tuiScrollTop from "@/components/scroll-top/scroll-top"

	export default {
		mixins: [workorderbehavior, permissionCommon],
		components: {
			tuiScrollTop,
			ReservationPoPup,
			VisitPoPup,
			WoItem,
			SearchBar,
			Tabs,
			AGInput,
			appraisePopup
		},
		data() {
			return {
				workOrderList: [],
				current: 0,
				pageNum: 1,
				VisitData: {
					Milestone: 0,
					Location: "",
					currentLongitude: 0,
					currentLatitude: 0,
					accountLongitude: 0,
					accountLatitude: 0
				},
				orderDetailData: {},
				//经度
				currentLongitude: 0,
				//纬度
				currentLatitude: 0,
				//当前用户定位地址
				userPosition: '',
				//客户的经纬度
				accountLongitude: 0,
				accountLatitude: 0,
				//评价二维吗
				qrAppraise: '',
				//距离-公里
				distance: 0,

				//定位是否成功
				IsLocationSuccess: false,
				scrollTop:0
			}
		},
		watch: {
			//监视公里数是否发生变化
			//         'VisitData.Milestone':{
			//    handler(newval, oldval) {
			//         if(newval!=oldval)
			// 		this.VisitData.Milestone = newval;
			//    },
			//    immediate: true,
			//   }
		},
		computed: {
			workOrderState() {
				if (this.current === 2) //提交完工
					return 4;
				else if (this.current == 3)
					return 3; //已完工
				else //待接单,待处理
					return this.current + 1;
			},
		},
		mounted() {
			//debugger;
			uni.$on('ReLoadWorder', () => {
				//debugger;
				this.RefreshWorkOrder();
			});
			uni.showLoading({
				title: "加载...",
				mask: true
			})

			this.getPageWorderOrderStateAsync();
		},
		onLoad(e) {
			//debugger;
			uni.$on('ReLoadWorder', () => {
				this.RefreshWorkOrder();
			});
			uni.showLoading({
				title: "加载...",
				mask: true
			})
			this.getPageWorderOrderStateAsync();
			//console.log("上下文"+this.$refs);
		},
		onUnload() {
			uni.$off("ReLoadWorder");
		},
		onShow(e) {

			let menuconfig = this.IsDisplayTab();
			if (!menuconfig.isAcceptingTapAuth && !menuconfig.isProcessingTapAuth &&
				!menuconfig.isSubmittedTapAuth && !menuconfig.isDoneTapAuth) {
				uni.navigateBack()
			} else {
				this.tabs[0].isdisplay = menuconfig.isAcceptingTapAuth;
				this.tabs[1].isdisplay = menuconfig.isProcessingTapAuth;
				this.tabs[2].isdisplay = menuconfig.isSubmittedTapAuth;
				this.tabs[3].isdisplay = menuconfig.isDoneTapAuth;
			}
		},
		onPullDownRefresh(e) {
			uni.showLoading({
				title: "加载...",
				mask: true
			})
			uni.showNavigationBarLoading();
			this.workOrderList = [];
			this.pageNum = 1;
			let hideMyLoading = () => {

				uni.stopPullDownRefresh();
				uni.hideLoading();
				uni.hideNavigationBarLoading();
			}
			this.getPageWorderOrderStateAsync(hideMyLoading);

		},
		onReachBottom(e) {
			uni.showLoading({
				title: "加载...",
				mask: true
			})
			console.log("onReachBottom")
			this.pageNum = this.pageNum + 1;
			this.getPageWorderOrderStateAsync();
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		methods: {
			towOrderSearch(e) {
				console.log(e);
				let searchWord = e || "";
				uni.navigateTo({
					url: `../wosearch/index?searchWord=${searchWord}`
				})
			},
			onvaluateClick(e) {
				//console.log(e);
				let woNum = e.workorder.WoNum
				this.WeChatExpAsync().then((result) => {
					//debugger;
					this.qrAppraise = result.RetObject.replace("[code]", woNum);
					console.log(this.qrAppraise)
					this.$refs.appraisePopup.openPoPup()
				});

			},
			onCompleteWOrder(e) {
				console.log(e);
				//permissionCommon
				this.GoToPage(e.workorder.WoFinishType, e.workorder.WoId);
			},
			onReCompleteWOrder(e) {
				//permissionCommon
				this.GoToPage(e.workorder.WoFinishType, e.workorder.WoId);
			},
			onChangeStreet(e) {
				this.orderDetailData.Street = e;
				console.log(e);
			},
			onChangeMilestone(e) {
				this.VisitData.Milestone = e;
				console.log(e);
			},
			async openAddressMap(e) {
				let token = this.UserInfo.RetId;
				let locationMap = await this.getAddressMapAsync(e.adddress)
				//console.log(locationMap);

				uni.openLocation({
					latitude: locationMap.result.location.lat,
					longitude: locationMap.result.location.lng,
					success: function() {
						console.log('success');
					}
				});
			},


			//上门按钮
			onVisitClick(e) {
				console.log(e.workorder);
				this.resetVisiData();
				this.orderDetailData = e.workorder;
				this.VisitPoPupOpen();
				//debugger;
				this.GetUserLocation();
			},

			resetVisiData() {
				this.VisitData.currentLongitude = "";
				this.VisitData.currentLatitude = "";
				this.VisitData.Location = "";
				this.VisitData.accountLongitude = "";
				this.VisitData.accountLatitude = "";
			},

			//上门弹框确定按钮
			onSubmitVisit(e) {
				console.log(this.orderDetailData);
				console.log(this.VisitData);
				console.log(e);
				let VisitSubmitData = {};
				VisitSubmitData.UserId = this.UserInfo.mobile;
				VisitSubmitData.WOGUID = this.orderDetailData.WoId;
				VisitSubmitData.Longitude = this.VisitData.accountLongitude;
				VisitSubmitData.Latitude = this.VisitData.accountLatitude;
				VisitSubmitData.Location = this.VisitData.Location;
				VisitSubmitData.NewAddress = this.orderDetailData.Street;
				VisitSubmitData.Milestone = this.VisitData.Milestone;
				VisitSubmitData.IsLocationSuccess = this.VisitData.IsLocationSuccess;
				VisitSubmitData.Remark = e.vitisRemark;
				uni.showLoading({
					mask: true,
					title: "提交中..",
				})
				if (VisitSubmitData.IsLocationSuccess == true) {
					if (VisitSubmitData.Milestone != 0 && VisitSubmitData.NewAddress != '') {
						this.WoFieldServiceAsync(VisitSubmitData, this.UserInfo.RetId);

					} else {
						uni.hideLoading();
						uni.showToast({
							title: "请填写更正地址与上门里程",
							icon: "none"
						});
					}
				} else {
					uni.hideLoading();
					uni.showToast({
						title: "定位失败，无法计算里程，无法上门",
						icon: "none"
					});
					this.$refs.visitPoPup.closePoPup();
				}
			},

			//打开预约窗口
			onReservationClick(e) {
				console.log(e.workorder);
				this.orderDetailData = e.workorder;

				this.$refs.reservationPoPup.openPoPup();
			},
			//预约提交
			async onSubmitReservation(e) {
				uni.showLoading({
					mask: true,
					title: "提交中..",
				})
				if (e.reservationTime && e.ReasonCodeId) {
					this.OrderReservationAsync(e.reservationTime, e.reservationRemark,
						e.ReasonCodeId);
				} else {
					uni.hideLoading();
					uni.showToast({
						title: "预约时间与预约原因需要填写",
						icon: "none"
					});
				}
			},
			//接单
			onAcceptorderClick(e) {
				uni.showLoading({
					mask: true,
					title: "接单中..",
				})
				this.AcceptorderAsync(e.WoId).then((result) => {
					//debugger;
					uni.hideLoading();
					console.log("接单接口：" + result);
					if (result.RetBool == true) {
						uni.showToast({
							title: "接单成功",
							icon: "none"
						});
						this.RefreshWorkOrder()
					} else {
						uni.showToast({
							title: result.RetMsg,
							icon: "none",
							duration: 2000
						});
					}
				}, (err) => {
					uni.hideLoading();
				}).catch((ex) => {
					uni.hideLoading();
				});
			},

			displayBtn: function(woitem) {
				let tabId = this.current;
				let showBtnResult = this.showBtn(woitem);
				//console.log(showBtnResult)
				return showBtnResult;
			},




			firstChar: function(str) {
				if (str)
					return str.charAt(0);
				else
					return ""
			},

			onTabChange(e) {
				//console.log(e);
				uni.showLoading({
					title: "加载...",
					mask: true
				})
				this.current = e.current;
				this.workOrderList = [];
				this.pageNum = 1;
				this.getPageWorderOrderStateAsync();
			},
		}
	}
</script>
<style lang="scss">
	@import './index.scss';
</style>
